package com.appspot.showup_app.showup;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.appspot.showup_app.showup.model.ShowUpAppointmentMessage;
import com.appspot.showup_app.showup.tasks.DeleteAppointmentTask;

import static android.support.v4.app.ActivityCompat.startActivityForResult;

public class AgendaAdapter extends BaseAdapter {

    private static final int APT_ID = 0;
    List<ShowUpAppointmentMessage> mAppointments;
    Context mContext;

    private LayoutInflater mInflater;

    public AgendaAdapter(Context context, List<ShowUpAppointmentMessage> appointments) {
        mAppointments = appointments;
        mContext = context;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return mAppointments.size();
    }

    public ShowUpAppointmentMessage getItem(int position) {
        return mAppointments.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.appointment_list_item, null);

            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            // insert into holder all the views you wan to use

            holder.txtDayOfWeek = (TextView) convertView.findViewById(R.id.txt_day_of_week);
            holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
            holder.itemLayout = (RelativeLayout) convertView.findViewById(R.id.item_layout);
            holder.dateTitleLayout = (RelativeLayout) convertView.findViewById(R.id.date_title_layout);
            holder.aptStatusColor = (TextView) convertView.findViewById(R.id.apt_status_color);
            holder.txtStartTime = (TextView) convertView.findViewById(R.id.txt_start_time);
            holder.txtDuration = (TextView) convertView.findViewById(R.id.txt_duration);
            holder.txtCustomerName = (TextView) convertView.findViewById(R.id.txt_customer_name);
            holder.txtCustomerPhone = (TextView) convertView.findViewById(R.id.txt_customer_phone);
            holder.txtCustomerAddress = (TextView) convertView.findViewById(R.id.txt_customer_address);
            holder.txtAppointmentNotes = (TextView) convertView.findViewById(R.id.txt_apt_notes);
            holder.btnEditAppointment = (ImageButton) convertView.findViewById(R.id.btn_edit_apt);
            holder.btnDeleteAppointment = (ImageButton) convertView.findViewById(R.id.btn_delete_apt);
            holder.aptMoreDetails = (RelativeLayout) convertView.findViewById(R.id.apt_more_details);
            holder.aptMainDetails = (RelativeLayout) convertView.findViewById(R.id.apt_main_details);
            holder.addAppointment = (TextView) convertView.findViewById(R.id.add_appointment);
            holder.aptMoreDetails.setVisibility(View.GONE);


            holder.itemLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.aptMoreDetails.setVisibility(holder.aptMoreDetails.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
                }
            });

            holder.btnEditAppointment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, AddEditAppointmentActivity.class);
                    intent.putExtra("APPOINTMENT_ID", (String) (v.getTag()));
                    ((Activity)mContext).startActivityForResult(intent, 0);
                }
            });

            holder.btnDeleteAppointment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new AlertDialog.Builder(mContext)
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setTitle("Delete Appointment")
                            .setMessage("Are you sure?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final ProgressDialog progressDialog = new ProgressDialog(mContext);
                                    progressDialog.setMessage("Deleting appointment...");
                                    progressDialog.show();
                                    DeleteAppointmentTask deleteAppointmentTask = new DeleteAppointmentTask(mContext, (String)holder.btnDeleteAppointment.getTag()) {
                                        @Override
                                        protected void onPostExecute(Void success) {
                                            DatabaseHelper.deleteAppointment(((AgendaActivity) mContext).db, this.mAppointmentId);
                                            mAppointments.remove(position);
                                            AgendaAdapter.this.notifyDataSetChanged();
                                            progressDialog.dismiss();
                                        }

                                    };
                                    deleteAppointmentTask.execute((Void) null);
                                }
                            })
                            .setNegativeButton("No", null)
                            .show();
                }
            });

            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }

        final ShowUpAppointmentMessage appointmentMessage = getItem(position);

        Date startTime = DateTimeUtil.fromTimestamp(appointmentMessage.getStartTime());
        long duration = appointmentMessage.getDuration();

        holder.addAppointment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AddEditAppointmentActivity.class);
                intent.putExtra("START_TIME", appointmentMessage.getStartTime());
                ((Activity)mContext).startActivityForResult(intent, 0);
            }
        });

        boolean showTitle = true;
        if (position > 0) {
            ShowUpAppointmentMessage prevAppointment = getItem(position - 1);
            Date prevStartTime = DateTimeUtil.fromTimestamp(prevAppointment.getStartTime());
            if (DateTimeUtil.dateStr(prevStartTime).equals(DateTimeUtil.dateStr(startTime)))
                showTitle = false;
        }
        boolean showFooter = true;
        if (position < getCount()-1) {
            ShowUpAppointmentMessage nextAppointment = getItem(position + 1);
            Date nextStartTime = DateTimeUtil.fromTimestamp(nextAppointment.getStartTime());
            if (DateTimeUtil.dateStr(nextStartTime).equals(DateTimeUtil.dateStr(startTime)))
                showFooter = false;
        }

        holder.dateTitleLayout.setVisibility(showTitle ? View.VISIBLE : View.GONE);
        holder.addAppointment.setVisibility(showFooter ? View.VISIBLE : View.GONE);

        if (showTitle) {
            holder.txtDayOfWeek.setText(DateTimeUtil.dayOfWeekStr(startTime).toUpperCase());
            holder.txtDate.setText(DateTimeUtil.dateStr(startTime));
            if (DateTimeUtil.dateStr(startTime).equals(DateTimeUtil.dateStr(new Date())))
                holder.txtDayOfWeek.setTextColor(Color.parseColor("#2FACA6"));
            else
                holder.txtDayOfWeek.setTextColor(Color.parseColor("#555555"));
        }

        switch (appointmentMessage.getConfirmationStatus().intValue()) {
            case 0:
            case 1:
                holder.aptStatusColor.setTextColor(Color.parseColor("#eeeeee"));
                break;
            case 2:
                holder.aptStatusColor.setTextColor(Color.parseColor("#b3ef92"));
                break;
            case 3:
                holder.aptStatusColor.setTextColor(Color.parseColor("#ef9292"));
                break;
        }

        holder.txtStartTime.setText(String.format("%s", DateTimeUtil.hoursStr(startTime)));
        holder.txtDuration.setText(String.format("%d min", duration));
        holder.txtCustomerName.setText(appointmentMessage.getCustomer().getName());
        holder.txtCustomerAddress.setText(appointmentMessage.getCustomer().getAddress());
        holder.txtCustomerPhone.setText(appointmentMessage.getCustomer().getPhoneNumber());
        holder.txtAppointmentNotes.setText(appointmentMessage.getNotes());
        holder.btnDeleteAppointment.setTag(appointmentMessage.getId().toString());
        holder.btnEditAppointment.setTag(appointmentMessage.getId().toString());

        return convertView;
    }


    static class ViewHolder {
        RelativeLayout dateTitleLayout;
        TextView txtDayOfWeek;
        TextView txtDate;
        RelativeLayout itemLayout;
        TextView aptStatusColor;
        TextView txtStartTime;
        TextView txtDuration;
        TextView txtCustomerName;
        TextView txtCustomerPhone;
        TextView txtCustomerAddress;
        TextView txtAppointmentNotes;
        ImageButton btnEditAppointment;
        ImageButton btnDeleteAppointment;
        RelativeLayout aptMoreDetails;
        TextView addAppointment;
        RelativeLayout aptMainDetails;
    }

}


